﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DWEIP.Common;
using DataWin.Core.Model;
using DataWin.Core.Util;
using DWEIP.BLL.Core;
using DWEIP.Models.MIS;
using DWEIP.Models;
using DWEIP.BLL.Sys;

namespace DWEIP.BLL.MIS
{
    public partial class MIS_WebIM_MessageBLL : BasicBLL
    {
        SysUserBLL userBLL = new SysUserBLL();

        #region DAL
        /// <summary>
        /// 新增消息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="message"></param>
        /// <param name="sender"></param>
        /// <param name="receiver"></param>
        public void DAL_CreateMessage(string id, string message, string sender, string receiver, string receiverTitle)
        {
            Table _asp_CreateMessage = new Table("asp_CreateMessage");
            _asp_CreateMessage.Params["as_id"] = new Data(id);
            _asp_CreateMessage.Params["as_message"] = new Data(message);
            _asp_CreateMessage.Params["as_sender"] = new Data(sender);
            _asp_CreateMessage.Params["as_receiver"] = new Data(receiver);
            _asp_CreateMessage.Params["as_receiverTitle"] = new Data(receiverTitle);

            _asp_CreateMessage.Execute(System.Data.CommandType.StoredProcedure, true);
        }

        /// <summary>
        /// 删除发送者的一个消息(物理删除)
        /// </summary>
        /// <param name="id"></param>
        public void DAL_DeleteMessageBySender(string id)
        {
            Table _asp_MIS_DeleteMessageAllByReceiver = new Table("asp_MIS_DeleteMessageAllByReceiver");
            _asp_MIS_DeleteMessageAllByReceiver.Params["as_id"] = new Data(id);

            _asp_MIS_DeleteMessageAllByReceiver.Execute(System.Data.CommandType.StoredProcedure, true);
        }

        /// <summary>
        /// 删除发送者的所有消息（物理删除）
        /// </summary>
        /// <param name="sender"></param>
        public void DAL_DeleteMessageAllBySender(string sender)
        {
            Table _asp_MIS_DeleteMessageAllBySender = new Table("asp_MIS_DeleteMessageAllByReceiver");
            _asp_MIS_DeleteMessageAllBySender.Params["as_sender"] = new Data(sender);

            _asp_MIS_DeleteMessageAllBySender.Execute(System.Data.CommandType.StoredProcedure, true);
        }
        /// <summary>
        /// 删除发送者的多个消息(非物理删除)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="id"></param>
        public void DAL_DeleteMessageNotBySender(string sender, string[] ids)
        {
            //update MIS_WebIM_Message set State=true where ids.Contains(r.Id) and Sender == sender
        }
        /// <summary>
        /// 删除发送者的全部消息(非物理删除)
        /// </summary>
        /// <param name="sender"></param>
        public void DAL_DeleteMessageAllNotBySender(string sender)
        {
            //update MIS_WebIM_Message set State=true where Sender == sender
        }
        /// <summary>
        /// 删除接收者的一个消息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="?"></param>
        public void DAL_DeleteMessageByReceiver(string id, string receiver)
        {
            Table _asp_MIS_DeleteMessageByReceiver = new Table("asp_MIS_DeleteMessageByReceiver");
            _asp_MIS_DeleteMessageByReceiver.Params["as_id"] = new Data(id);
            _asp_MIS_DeleteMessageByReceiver.Params["as_receiver"] = new Data(receiver);

            _asp_MIS_DeleteMessageByReceiver.Execute(System.Data.CommandType.StoredProcedure, true);
        }
        /// <summary>
        /// 删除接收者的所有消息
        /// </summary>
        /// <param name="receiver"></param>
        public void DAL_DeleteMessageAllByReceiver(string receiver)
        {
            Table _asp_MIS_DeleteMessageAllByReceiver = new Table("asp_MIS_DeleteMessageAllByReceiver");
            _asp_MIS_DeleteMessageAllByReceiver.Params["as_receiver"] = new Data(receiver);

            _asp_MIS_DeleteMessageAllByReceiver.Execute(System.Data.CommandType.StoredProcedure, true);
        }

        /// <summary>
        /// 设置接收者的所有未阅读消息为已阅
        /// </summary>
        /// <param name="receiver"></param>
        public void DAL_SetMessageHasReadByReceiver(string receiver)
        {
            Table _asp_MIS_SetMessageHasReadByReceiver = new Table("asp_MIS_SetMessageHasReadByReceiver");
            _asp_MIS_SetMessageHasReadByReceiver.Params["as_receiver"] = new Data(receiver);

            _asp_MIS_SetMessageHasReadByReceiver.Execute(System.Data.CommandType.StoredProcedure, true);
        }
        public void DAL_SetMessageHasReadFromSenderToReceiver(string sender, string receiver)
        {
            Table _asp_MIS_SetMessageHasReadFromSenderToReceiver = new Table("asp_MIS_SetMessageHasReadFromSenderToReceiver");
            _asp_MIS_SetMessageHasReadFromSenderToReceiver.Params["as_sender"] = new Data(sender);
            _asp_MIS_SetMessageHasReadFromSenderToReceiver.Params["as_receiver"] = new Data(receiver);

            _asp_MIS_SetMessageHasReadFromSenderToReceiver.Execute(System.Data.CommandType.StoredProcedure, true);
        }
        /// <summary>
        /// 设置接收者的一条未阅读消息为已阅
        /// </summary>
        /// <param name="receiver"></param>
        /// <param name="id"></param>
        public void DAL_SetMessageHasReadById(string receiver, string id)
        {
            Table _asp_MIS_SetMessageHasReadFromSenderToReceiver = new Table("asp_MIS_SetMessageHasReadFromSenderToReceiver");
            _asp_MIS_SetMessageHasReadFromSenderToReceiver.Params["as_receiver"] = new Data(receiver);
            _asp_MIS_SetMessageHasReadFromSenderToReceiver.Params["as_id"] = new Data(id);

            _asp_MIS_SetMessageHasReadFromSenderToReceiver.Execute(System.Data.CommandType.StoredProcedure, true);
        }
        /// <summary>
        /// 返回发送信息给当前用户的发送者列表及未阅读信息数
        /// </summary>
        /// <param name="receiver"></param>
        /// <returns></returns>
        public List<MIS_WebIM_SenderModel> DAL_GetSenderByReceiver(string receiver)
        {
            Table _asp_MIS_GetSenderByReceiver = new Table("asp_MIS_GetSenderByReceiver");
            _asp_MIS_GetSenderByReceiver.Params["as_receiver"] = new Data(receiver);

            _asp_MIS_GetSenderByReceiver.Execute(System.Data.CommandType.StoredProcedure, true);

            var modelList = from r in _asp_MIS_GetSenderByReceiver
                            select new MIS_WebIM_SenderModel
                            {
                                Sender = r["Sender"].AsString,
                                SenderTitle = r["SenderTitle"].AsString,
                                MessageCount = r["MessageCount"].AsInt
                            };
            return modelList.ToList();
        }
        /// <summary>
        /// 读取一个发送消息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public MIS_WebIM_Message DAL_GetMessageBySender(string id)
        {
            MIS_WebIM_Message mIS_WebIM_Message = new MIS_WebIM_Message();

            //select * from MIS_WebIM_Message where Id = id

            return mIS_WebIM_Message;
        }
        /// <summary>
        /// 返回用户的所有通信记录
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="pageno"></param>
        /// <param name="rows"></param>
        /// <param name="rowscount"></param>
        /// <returns></returns>
        public List<MIS_WebIM_MessageModel> DAL_GetMessage(string userId, int pageno, int rows, ref int rowscount)
        {
            List<MIS_WebIM_MessageModel> mIS_WebIM_Messages = new List<MIS_WebIM_MessageModel>();

            Table _asp_MIS_GetMessage = new Table("asp_MIS_GetMessage");
            _asp_MIS_GetMessage.Params["as_rowscount"] = new Data(rowscount);

            _asp_MIS_GetMessage.Execute(System.Data.CommandType.StoredProcedure, true);

            var msgModelList = (from r in _asp_MIS_GetMessage
                                select new MIS_WebIM_MessageModel
                                {
                                    Id = r["Id"].AsString,
                                    Message = r["Message"].AsString,
                                    Sender = r["Sender"].AsString,
                                    receiver = r["receiver"].AsString,
                                    State = r["State"].AsBoolean,
                                    SendDt = r["SendDt"].AsDateTime,
                                    receiverTitle = r["receiverTitle"].AsString
                                }).ToList();
            return msgModelList;
        }

        /// <summary>
        /// 发送者发送的全部消息
        /// </summary>
        /// <param name="db"></param>
        /// <returns></returns>
        public IQueryable<MIS_WebIM_Message> DAL_GetMesasgeAllBySender()
        {
            Table _MIS_WebIM_Message = new Table("MIS_WebIM_Message");
            _MIS_WebIM_Message.SQL.Value = @"
SELECT * FROM MIS_WebIM_Message";
            BLLSession.Load(_MIS_WebIM_Message);

            var msgModelList = (from r in _MIS_WebIM_Message
                                select new MIS_WebIM_Message
                                {
                                    Id = r["Id"].AsString,
                                    Message = r["Message"].AsString,
                                    Sender = r["Sender"].AsString,
                                    receiver = r["receiver"].AsString,
                                    State = r["State"].AsBoolean,
                                    SendDt = r["SendDt"].AsDateTime,
                                    receiverTitle = r["receiverTitle"].AsString
                                }).ToList().AsQueryable();

            return msgModelList;
        }
        /// <summary>
        /// 返回接收者一个消息
        /// </summary>
        /// <param name="receiver"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public MIS_WebIM_MessageRecModel DAL_GetMessageByReceiver(string receiver, string id)
        {
            Table _MIS_WebIM_Message = new Table("MIS_WebIM_Message");
            _MIS_WebIM_Message.SQL.Value = @"
SELECT aa.Id, aa.Message,aa.Sender,bb.receiver,bb.State,aa.SendDt,bb.RecDt FROM MIS_WebIM_Message aa
JOIN MIS_WebIM_Message_Rec bb on aa.Id=bb.MessageId
WHERE aa.Id=@id and bb.receiver = @receiver";
            _MIS_WebIM_Message.Params.Add("id", new Data(id));
            _MIS_WebIM_Message.Params.Add("receiver", new Data(receiver));

            BLLSession.Load(_MIS_WebIM_Message);

            var model = (from m in _MIS_WebIM_Message
                         select new MIS_WebIM_MessageRecModel
                         {
                             Id = m["Id"].AsString,
                             Message = m["Message"].AsString,
                             Sender = m["Sender"].AsString,
                             receiver = m["receiver"].AsString,
                             State = m["State"].AsBoolean,
                             SendDt = m["SendDt"].AsDateTime,
                             RecDt = m["RecDt"].AsDateTime
                         }).SingleOrDefault();
            return model;
        }

        /// <summary>
        /// 返回接收者所有消息
        /// </summary>
        /// <param name="receiver"></param>
        /// <returns></returns>
        public IQueryable<MIS_WebIM_MessageRecModel> DAL_GetMessageAllByReceiver(string receiver)
        {
            Table _MIS_WebIM_Message = new Table("MIS_WebIM_Message");
            _MIS_WebIM_Message.SQL.Value = @"
SELECT aa.Id, aa.Message,aa.Sender,bb.receiver,bb.State,aa.SendDt,bb.RecDt FROM MIS_WebIM_Message aa
JOIN MIS_WebIM_Message_Rec bb on aa.Id=bb.MessageId
WHERE bb.receiver = @receiver";
            _MIS_WebIM_Message.Params.Add("receiver", new Data(receiver));
            BLLSession.Load(_MIS_WebIM_Message);

            var msgModelList = (from r in _MIS_WebIM_Message
                                select new MIS_WebIM_MessageRecModel
                                {
                                    Id = r["Id"].AsString,
                                    Message = r["Message"].AsString,
                                    Sender = r["Sender"].AsString,
                                    receiver = r["receiver"].AsString,
                                    State = r["State"].AsBoolean,
                                    SendDt = r["SendDt"].AsDateTime,
                                    receiverTitle = r["receiverTitle"].AsString
                                }).ToList().AsQueryable();

            return msgModelList;
        }
        #endregion DAL


        /// <summary>
        /// 新增消息
        /// </summary>
        /// <param name="validationErrors"></param>
        /// <param name="message">消息内容</param>
        /// <param name="sender">发送者(当前用户ID)</param>
        /// <param name="receiver">接收者</param>
        /// <param name="receiverTitle">接收者标题名称</param>
        /// <returns></returns>
        public string CreateMessage(ref ValidationErrors validationErrors, string message, string sender, string receiver, string receiverTitle)
        {
            try
            {
                if (string.IsNullOrEmpty(message))
                {
                    validationErrors.Add("消息内容不能为空");
                    return null;
                }
                if (string.IsNullOrEmpty(receiver))
                {
                    validationErrors.Add("接者不能为空");
                    return null;
                }
                if (string.IsNullOrEmpty(receiverTitle))
                {
                    validationErrors.Add("接者不能为空");
                    return null;
                }

                string id = Guid.NewGuid().ToString();
                DAL_CreateMessage(id, message, sender, receiver, receiverTitle);
                return id;
            }
            catch (Exception ex)
            {
                validationErrors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return null;
            }
        }
        /// <summary>
        /// 新增消息
        /// </summary>
        /// <param name="validationErrors"></param>
        /// <param name="id">消息ID</param>
        /// <param name="message">消息内容</param>
        /// <param name="sender">发送者(当前用户ID)</param>
        /// <param name="receiver">接收者</param>
        /// <param name="receiverTitle">接收者标题名称</param>
        /// <returns></returns>
        public bool CreateMessage(ref ValidationErrors validationErrors, string id, string message, string sender, string receiver, string receiverTitle)
        {
            try
            {
                DAL_CreateMessage(id, message, sender, receiver, receiverTitle);
                return true;
            }
            catch (Exception ex)
            {
                validationErrors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }
        /// <summary>
        /// 新增消息
        /// </summary>
        /// <param name="validationErrors"></param>
        /// <param name="model">消息模型</param>
        /// <returns></returns>
        public bool CreateMessage(ref ValidationErrors validationErrors, MIS_WebIM_MessageModel model)
        {
            try
            {
                DAL_CreateMessage(model.Id, model.Message, model.Sender, model.receiver, model.receiverTitle);
                return true;
            }
            catch (Exception ex)
            {
                validationErrors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }
        /// <summary>
        /// 删除接收者的所有消息
        /// </summary>
        /// <param name="validationErrors"></param>
        /// <param name="receiver">接收者</param>
        /// <returns></returns>
        public bool DeleteMessageAllByReceiver(ref ValidationErrors validationErrors, string receiver)
        {
            try
            {
                DAL_DeleteMessageAllByReceiver(receiver);
                return true;
            }
            catch (Exception ex)
            {
                validationErrors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }
        /// <summary>
        /// 删除用户消息
        /// </summary>
        /// <param name="validationErrors"></param>
        /// <param name="userId"></param>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool DeleteMessageByUserId(ref ValidationErrors validationErrors, string userId, string[] ids)
        {
            try
            {
                DAL_DeleteMessageNotBySender(userId, ids);

                for (int i = 0; i < ids.Length; i++)
                {
                    DAL_DeleteMessageByReceiver(ids[i], userId);
                }
                return true;
            }
            catch (Exception ex)
            {
                validationErrors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }
        /// <summary>
        /// 删除用户所有消息
        /// </summary>
        /// <param name="validationErrors"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool DeleteMessageByUserId(ref ValidationErrors validationErrors, string userId)
        {
            try
            {
                DAL_DeleteMessageAllNotBySender(userId);

                DAL_DeleteMessageAllByReceiver(userId);
                return true;
            }
            catch (Exception ex)
            {
                validationErrors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }
        /// <summary>
        /// 删除发送者的所有消息
        /// </summary>
        /// <param name="validationErrors"></param>
        /// <param name="sender">发送者(当前用户ID)</param>
        /// <returns></returns>
        public bool DeleteMessageAllBySender(ref ValidationErrors validationErrors, string sender)
        {
            try
            {
                DAL_DeleteMessageAllBySender(sender);
                return true;
            }
            catch (Exception ex)
            {
                validationErrors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }
        /// <summary>
        /// 删除接收者的一个消息
        /// </summary>
        /// <param name="validationErrors"></param>
        /// <param name="id">消息ID</param>
        /// <param name="receiver">接收者</param>
        /// <returns></returns>
        public bool DeleteMessageByReceiver(ref ValidationErrors validationErrors, string id, string receiver)
        {
            try
            {
                DAL_DeleteMessageByReceiver(id, receiver);
                return true;
            }
            catch (Exception ex)
            {
                validationErrors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }
        /// <summary>
        /// 删除发送者的一个消息
        /// </summary>
        /// <param name="validationErrors"></param>
        /// <param name="id">消息ID</param>
        /// <returns></returns>
        public bool DeleteMessageBySender(ref ValidationErrors validationErrors, string id)
        {
            try
            {
                DAL_DeleteMessageBySender(id);
                return true;
            }
            catch (Exception ex)
            {
                validationErrors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }
        /// <summary>
        /// 返回用户的所有通信记录
        /// </summary>
        /// <param name="pager"></param>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        public List<MIS_WebIM_MessageModel> GetMessage(ref GridPager pager, string userId)
        {
            try
            {
                int rowscount = 0;
                List<MIS_WebIM_MessageModel> modelList = DAL_GetMessage(userId, pager.page, pager.rows, ref rowscount);

                pager.totalRows = rowscount;

                foreach (var model in modelList)
                {
                    model.SenderTitle = userBLL.DAL_GetNameById(model.Sender);
                }
                return modelList;
            }
            catch (Exception ex)
            {
                ExceptionHander.WriteException(ex);
                return null;
            }

        }
        /// <summary>
        /// 发送者发送的全部消息
        /// </summary>
        /// <param name="pager"></param>
        /// <param name="sender">发送者(当前用户ID)</param>
        /// <returns></returns>
        public List<MIS_WebIM_MessageModel> GetMesasgeAllBySender(ref GridPager pager, string sender)
        {
            try
            {
                IQueryable<MIS_WebIM_Message> queryData = DAL_GetMesasgeAllBySender().Where(a => a.Sender == sender).OrderByDescending(a => a.Id);

                pager.totalRows = queryData.Count();
                if (pager.totalRows > 0)
                {
                    if (pager.page <= 1)
                    {
                        queryData = queryData.Take(pager.rows);
                    }
                    else
                    {
                        queryData = queryData.Skip((pager.page - 1) * pager.rows).Take(pager.rows);
                    }
                }
                List<MIS_WebIM_MessageModel> modelList = (from r in queryData
                                                          select new MIS_WebIM_MessageModel
                                                          {
                                                              Id = r.Id,
                                                              Message = r.Message,
                                                              Sender = r.Sender,
                                                              receiver = r.receiver,
                                                              State = r.State,
                                                              SendDt = r.SendDt,
                                                          }).ToList();
                foreach (var model in modelList)
                {
                    model.SenderTitle = userBLL.DAL_GetNameById(model.Sender);
                    model.receiverTitle = userBLL.DAL_GetNameById(model.receiver);
                }
                return modelList;
            }
            catch (Exception ex)
            {

                ExceptionHander.WriteException(ex);
                return null;
            }
        }
        /// <summary>
        /// 返回接收者所有消息        
        /// </summary>
        /// <param name="pager"></param>
        /// <param name="receiver">接收者</param>
        /// <returns></returns>
        public List<MIS_WebIM_MessageRecModel> GetMessageAllByReceiver(ref GridPager pager, string receiver)
        {
            try
            {
                IQueryable<MIS_WebIM_MessageRecModel> queryData = DAL_GetMessageAllByReceiver(receiver).Where(a => a.receiver == receiver).OrderByDescending(a => a.SendDt);

                pager.totalRows = queryData.Count();
                if (pager.totalRows > 0)
                {
                    if (pager.page <= 1)
                    {
                        queryData = queryData.Take(pager.rows);
                    }
                    else
                    {
                        queryData = queryData.Skip((pager.page - 1) * pager.rows).Take(pager.rows);
                    }
                }

                List<MIS_WebIM_MessageRecModel> modelList = (from r in queryData
                                                             select new MIS_WebIM_MessageRecModel
                                                             {
                                                                 Id = r.Id,
                                                                 Message = r.Message,
                                                                 Sender = r.Sender,
                                                                 receiver = r.receiver,
                                                                 State = r.State,
                                                                 SendDt = r.SendDt,
                                                                 RecDt = r.RecDt,
                                                             }).ToList();
                foreach (var model in modelList)
                {
                    model.SenderTitle = userBLL.DAL_GetNameById(model.Sender);
                    model.receiverTitle = userBLL.DAL_GetNameById(model.receiver);
                }

                return modelList;
            }
            catch (Exception ex)
            {
                ExceptionHander.WriteException(ex);
                return null;
            }
        }
        /// <summary>
        /// 返回接收者所有消息
        /// </summary>
        /// <param name="pager"></param>
        /// <param name="receiver">接收者</param>
        /// <param name="state">阅读状态,false未读,true已读</param>
        /// <returns></returns>
        public List<MIS_WebIM_MessageRecModel> GetMessageAllByReceiver(ref GridPager pager, string receiver, bool state)
        {
            try
            {
                IQueryable<MIS_WebIM_MessageRecModel> queryData = DAL_GetMessageAllByReceiver(receiver).Where(a => a.receiver == receiver && a.State == state).OrderByDescending(a => a.Id);

                pager.totalRows = queryData.Count();
                if (pager.totalRows > 0)
                {
                    if (pager.page <= 1)
                    {
                        queryData = queryData.Take(pager.rows);
                    }
                    else
                    {
                        queryData = queryData.Skip((pager.page - 1) * pager.rows).Take(pager.rows);
                    }
                }

                List<MIS_WebIM_MessageRecModel> modelList = (from r in queryData
                                                             select new MIS_WebIM_MessageRecModel
                                                             {
                                                                 Id = r.Id,
                                                                 Message = r.Message,
                                                                 Sender = r.Sender,
                                                                 receiver = r.receiver,
                                                                 State = r.State,
                                                                 SendDt = r.SendDt,
                                                                 RecDt = r.RecDt,
                                                             }).ToList();
                foreach (var model in modelList)
                {
                    model.SenderTitle = userBLL.DAL_GetNameById(model.Sender);
                    model.receiverTitle = userBLL.DAL_GetNameById(model.receiver);
                }

                return modelList;
            }
            catch (Exception ex)
            {
                ExceptionHander.WriteException(ex);
                return null;
            }
        }
        /// <summary>
        /// 返回指定发送者到接收者(未读/已读)消息
        /// </summary>
        /// <param name="pager"></param>
        /// <param name="sender">发送者</param>
        /// <param name="receiver">接收者</param>
        /// <param name="state">阅读状态,false未读,true已读</param>
        /// <returns></returns>
        public List<MIS_WebIM_MessageRecModel> GetMessageFromSenderToReceiver(ref GridPager pager, string sender, string receiver, bool state)
        {
            try
            {
                IQueryable<MIS_WebIM_MessageRecModel> queryData = DAL_GetMessageAllByReceiver(receiver).Where(a => a.Sender == sender && a.State == state).OrderByDescending(a => a.SendDt);

                pager.totalRows = queryData.Count();
                if (pager.totalRows > 0)
                {
                    if (pager.page <= 1)
                    {
                        queryData = queryData.Take(pager.rows);
                    }
                    else
                    {
                        queryData = queryData.Skip((pager.page - 1) * pager.rows).Take(pager.rows);
                    }
                }

                List<MIS_WebIM_MessageRecModel> modelList = (from r in queryData
                                                             select new MIS_WebIM_MessageRecModel
                                                             {
                                                                 Id = r.Id,
                                                                 Message = r.Message,
                                                                 Sender = r.Sender,
                                                                 receiver = r.receiver,
                                                                 State = r.State,
                                                                 SendDt = r.SendDt,
                                                                 RecDt = r.RecDt,
                                                             }).ToList();
                foreach (var model in modelList)
                {
                    model.SenderTitle = userBLL.DAL_GetNameById(model.Sender);
                    model.receiverTitle = userBLL.DAL_GetNameById(model.receiver);
                }

                return modelList;
            }
            catch (Exception ex)
            {
                ExceptionHander.WriteException(ex);
                return null;
            }
        }
        /// <summary>
        /// 返回指定发送者到接收者所有消息
        /// </summary>
        /// <param name="pager"></param>
        /// <param name="sender">发送者</param>
        /// <param name="receiver">接收者</param>
        /// <returns></returns>
        public List<MIS_WebIM_MessageRecModel> GetMessageFromSenderToReceiver(ref GridPager pager, string sender, string receiver)
        {
            try
            {
                IQueryable<MIS_WebIM_MessageRecModel> queryData = DAL_GetMessageAllByReceiver(receiver).Where(a => a.receiver == receiver && a.Sender == sender).OrderBy(a => a.SendDt);

                pager.totalRows = queryData.Count();
                if (pager.totalRows > 0)
                {
                    if (pager.page <= 1)
                    {
                        queryData = queryData.Take(pager.rows);
                    }
                    else
                    {
                        queryData = queryData.Skip((pager.page - 1) * pager.rows).Take(pager.rows);
                    }
                }

                List<MIS_WebIM_MessageRecModel> modelList = (from r in queryData
                                                             select new MIS_WebIM_MessageRecModel
                                                             {
                                                                 Id = r.Id,
                                                                 Message = r.Message,
                                                                 Sender = r.Sender,
                                                                 receiver = r.receiver,
                                                                 State = r.State,
                                                                 SendDt = r.SendDt,
                                                                 RecDt = r.RecDt,
                                                             }).ToList();
                foreach (var model in modelList)
                {
                    model.SenderTitle = userBLL.DAL_GetNameById(model.Sender);
                    model.receiverTitle = userBLL.DAL_GetNameById(model.receiver);
                }

                return modelList;
            }
            catch (Exception ex)
            {
                ExceptionHander.WriteException(ex);
                return null;
            }
        }
        /// <summary>
        /// 返回发送信息给当前用户的发送者列表及未阅读信息数
        /// </summary>
        /// <param name="receiver"></param>
        /// <returns></returns>
        public List<MIS_WebIM_SenderModel> GetSenderByReceiver(string receiver)
        {
            try
            {
                return DAL_GetSenderByReceiver(receiver);
            }
            catch (Exception ex)
            {
                ExceptionHander.WriteException(ex);
                return null;
            }
        }

        /// <summary>
        /// 返回接收者一个消息
        /// </summary>
        /// <param name="receiver">接收者</param>
        /// <param name="id">消息ID</param>
        /// <returns></returns>
        public MIS_WebIM_MessageRecModel GetMessageByReceiver(string receiver, string id)
        {
            try
            {
                return DAL_GetMessageByReceiver(receiver, id);

            }
            catch (Exception ex)
            {
                ExceptionHander.WriteException(ex);
                return null;
            }
        }
        /// <summary>
        /// 读取一个发送消息
        /// </summary>
        /// <param name="id">消息ID</param>
        /// <returns></returns>
        public MIS_WebIM_MessageModel GetMessageBySender(string id)
        {
            try
            {
                var entity = DAL_GetMessageBySender(id);
                if (entity == null)
                {
                    return null;
                }
                MIS_WebIM_MessageModel model = new MIS_WebIM_MessageModel();
                model.Id = entity.Id;
                model.Message = entity.Message;
                model.Sender = entity.Sender;
                model.receiver = entity.receiver;
                model.State = entity.State;
                model.SendDt = entity.SendDt;
                model.SenderTitle = userBLL.DAL_GetNameById(entity.Sender);
                model.receiverTitle = userBLL.DAL_GetNameById(entity.receiver);

                return model;

            }
            catch (Exception ex)
            {
                ExceptionHander.WriteException(ex);
                return null;
            }
        }
        /// <summary>
        /// 设置接收者的一条未阅读消息为已阅
        /// </summary>
        /// <param name="validationErrors"></param>
        /// <param name="receiver">接收者</param>
        /// <param name="id">消息ID</param>
        /// <returns></returns>
        public bool SetMessageHasReadById(ref ValidationErrors validationErrors, string receiver, string id)
        {
            try
            {
                DAL_SetMessageHasReadById(receiver, id);
                return true;
            }
            catch (Exception ex)
            {
                validationErrors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }
        /// <summary>
        /// 设置接收者的所有未阅读消息为已阅
        /// </summary>
        /// <param name="validationErrors"></param>
        /// <param name="receiver">接收者</param>
        /// <returns></returns>
        public bool SetMessageHasReadByReceiver(ref ValidationErrors validationErrors, string receiver)
        {
            try
            {
                DAL_SetMessageHasReadByReceiver(receiver);
                return true;
            }
            catch (Exception ex)
            {
                validationErrors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }
        /// <summary>
        /// 修改一发送者到接收者的所有未阅读消息为已阅状态
        /// </summary>
        /// <param name="validationErrors"></param>
        /// <param name="sender">发送者</param>
        /// <param name="receiver">接收者</param>
        /// <returns></returns>
        public bool SetMessageHasReadFromSenderToReceiver(ref ValidationErrors validationErrors, string sender, string receiver)
        {
            try
            {
                DAL_SetMessageHasReadFromSenderToReceiver(sender, receiver);
                return true;
            }
            catch (Exception ex)
            {
                validationErrors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }
    }
}
